
package com.yimixian.app.util;

import com.ta.utdid2.android.utils.StringUtils;
import com.yimixian.app.EventBusDomain.DialogDismissMessage;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.YMXApplication;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.cart.CouDanActivity;
import com.yimixian.app.cart.CouDanFragment;
import com.yimixian.app.cart.HuanGouActivity;
import com.yimixian.app.cart.HuanGouFragment;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.YmxActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.goods.DialogEffectActivity;
import com.yimixian.app.model.CartUpdate;
import com.yimixian.app.model.PromotionInfo;
import com.yimixian.app.rest.response.BaseResponse;
import com.yimixian.app.search.SearchActivity;
import com.yimixian.app.search.SearchFragment;
import com.yimixian.app.ui.MessageDialogView;
import com.yimixian.app.ui.ProgressDialogFragment;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.Toast;

import java.io.Serializable;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

public class UiUtils {
    private static long lastClickTime;

    private static Paint sDividerPaint;

    public static Map<String, Long> timeMap = new HashMap<>();
    private static int intevalTime = 15 * 60 * 1000;//页面刷新的间隔时间
    private static int noticeTime = 24 * 60 * 60 * 1000;//首页通知时间间隔
    private static int AdShowTime = 12 * 60 * 60 * 1000;//首页广告蒙层显示时间
    private static int listViewScrollTime = 400; //listview滚动到指定位置的时间
    private static Scroller scroller;
    private static int dialogTime = 300;

    static {
        sDividerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        sDividerPaint.setColor(0xffdadada);
    }

    public static Paint getDividerPaint() {
        return sDividerPaint;
    }

    public static ProgressDialogFragment showProgressDialog(Context context) {
        return showProgressDialog(context, SystemFramework.getInstance().getGlobalContext()
            .getString(R.string.loading), false);
    }

    public static Context getSafeActivity(Fragment fragment){
        if (fragment != null && fragment.isAdded()){
            return fragment.getActivity();

        }else{
            return YMXApplication.getInstance();
        }
    }

    public static boolean isHasDialog(Context context){
        FrameLayout parent = (FrameLayout) ((Activity) context).getWindow().findViewById(Window.ID_ANDROID_CONTENT);
        View view = parent.findViewWithTag("dialogView");
        return view == null ? false : true;
    }

    public static void hideDialog(final View dialog){
        hideDialog(dialog, true);
    }

    public static void hideDialog(final View dialog, boolean needAnim){
        try {
            if(dialog != null){
                if(needAnim){
                    Animation anim = dialog.findViewById(R.id.ll_dialog_container).getAnimation();
                    if(anim != null && anim.hasStarted()){
                        return;
                    }
                    ScaleAnimation scale = new ScaleAnimation(
                            1f, 0f, 1f, 0f,
                            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    scale.setDuration(dialogTime);
                    scale.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            ((FrameLayout) dialog.getParent()).removeView(dialog);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });
                    dialog.findViewById(R.id.ll_dialog_container).startAnimation(scale);
                    AlphaAnimation alpha = new AlphaAnimation(1f, 0);
                    alpha.setDuration(dialogTime);
                    alpha.setFillAfter(true);
                    dialog.findViewById(R.id.v_back).startAnimation(alpha);
                }else{
                    ((FrameLayout) dialog.getParent()).removeView(dialog);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static View showOKAndCancelDialog(Context context, String message, String okText, View.OnClickListener okListener,
                                               String cancelText, View.OnClickListener cancelListener){
        FrameLayout parent = (FrameLayout) ((Activity) context).getWindow().findViewById(Window.ID_ANDROID_CONTENT);
        View view = parent.findViewWithTag("dialogView");
        if(view != null)
            return view;
        view = LayoutInflater.from(context).inflate(R.layout.message_dialog_view2, null);
        view.setTag("dialogView");
        parent.addView(view);
        TextView content_text = (TextView) view.findViewById(R.id.content_text);
        content_text.setText(message);
        TextView cancel_text = (TextView) view.findViewById(R.id.cancel_text);
        cancel_text.setText(cancelText);
        cancel_text.setOnClickListener(cancelListener);
        TextView ok_text = (TextView) view.findViewById(R.id.confirm_text);
        ok_text.setText(okText);
        ok_text.setOnClickListener(okListener);
        ScaleAnimation scale = new ScaleAnimation(
                0f, 1.0f, 0f, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scale.setDuration(dialogTime);
        view.findViewById(R.id.ll_dialog_container).getLayoutParams().width = (int) (context.getResources().getDisplayMetrics().widthPixels * 0.7f);
        view.findViewById(R.id.ll_dialog_container).requestLayout();
        view.findViewById(R.id.ll_dialog_container).startAnimation(scale);
        AlphaAnimation alpha = new AlphaAnimation(0, 1f);
        alpha.setDuration(dialogTime);
        view.findViewById(R.id.v_back).startAnimation(alpha);
        return view;
    }

    public static View showOKDialog(Context context, String message, String okText, View.OnClickListener okListener){

        FrameLayout parent = (FrameLayout) ((Activity) context).getWindow().findViewById(Window.ID_ANDROID_CONTENT);
        View view = parent.findViewWithTag("dialogView");
        if(view != null)
            return view;
        view = LayoutInflater.from(context).inflate(R.layout.message_dialog_view2, null);
        view.setTag("dialogView");
        parent.addView(view);
        TextView content_text = (TextView) view.findViewById(R.id.content_text);
        content_text.setText(message);
        TextView ok_text = (TextView) view.findViewById(R.id.confirm_text);
        ok_text.setText(okText);
        ok_text.setOnClickListener(okListener);
        View button_divider = view.findViewById(R.id.button_divider);
        button_divider.setVisibility(View.GONE);
        View cancel_text = view.findViewById(R.id.cancel_text);
        cancel_text.setVisibility(View.GONE);

        ScaleAnimation scale = new ScaleAnimation(
                0f, 1.0f, 0f, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scale.setDuration(dialogTime);
        view.findViewById(R.id.ll_dialog_container).getLayoutParams().width = (int) (context.getResources().getDisplayMetrics().widthPixels * 0.7f);
        view.findViewById(R.id.ll_dialog_container).requestLayout();
        view.findViewById(R.id.ll_dialog_container).startAnimation(scale);
        AlphaAnimation alpha = new AlphaAnimation(0, 1f);
        alpha.setDuration(dialogTime);
        view.findViewById(R.id.v_back).startAnimation(alpha);
        final View view_ = view;
        view.findViewById(R.id.v_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideDialog(view_);
            }
        });
        return view;
    }

    public static Dialog showLoadingDialog(Context context, String text){
        return showLoadingDialog(context, text, false);
    }

    public static Dialog showLoadingDialog(Context context, String text, boolean cancelable){
        AlertDialog dialog = new AlertDialog.Builder(context, R.style.DialogBackStyle).create();
        dialog.show();
        View view = LayoutInflater.from(context).inflate(R.layout.loading_view, null);
        TextView tv_loading = (TextView) view.findViewById(R.id.loading_text);
        if(Strings.isNullOrEmpty(text)){
            tv_loading.setVisibility(View.GONE);
        }else{
            tv_loading.setVisibility(View.VISIBLE);
            tv_loading.setText(text);
        }
        dialog.setContentView(view);
        dialog.setCancelable(cancelable);
        return dialog;
    }

    public static ProgressDialogFragment showProgressDialog(Context context, String text) {
        return showProgressDialog(context, text, false);
    }

    public static ProgressDialogFragment showProgressDialog(Context context, String text,
                                                            boolean cancelable) {
        ProgressDialogFragment dialogFragment = new ProgressDialogFragment();
        Bundle args = new Bundle();
        args.putString(ProgressDialogFragment.ARGUMENT_TEXT, text);
        dialogFragment.setArguments(args);
        dialogFragment.setCancelable(cancelable);
        FragmentTransaction transaction = ((Activity) context).getFragmentManager()
            .beginTransaction();
        transaction.add(dialogFragment, "ymx_progress_dialog");
        transaction.commitAllowingStateLoss();
        return dialogFragment;
    }

    public static void failProgressDialog(ProgressDialogFragment dialogFragment, String text) {
        if (dialogFragment.isVisible()) {
            dialogFragment.setText(text);
            dialogFragment.setCancelable(true);
        }
    }

    public static ProgressDialogFragment dismiss(ProgressDialogFragment dialogFragment) {
        if (dialogFragment != null) {
            dialogFragment.dismissAllowingStateLoss();
        }
        return null;
    }

    public static void showToast(Context context, String text) {
        showToast(context, text, true);
    }

    public static void showToast(String text) {
        showToast(SystemFramework.getInstance().getGlobalContext(), text, true);
    }

    public static void showToast(Context context, String text, boolean cancelPreviousToast) {
        if (!(context instanceof YmxActivity) || !cancelPreviousToast) {
            Toast.makeText(context, text, Toast.LENGTH_LONG).show();
            return;
        }

        YmxActivity activity = (YmxActivity) context;

        if (activity.hasToast()) {
            activity.getToast().cancel();
        }
        activity.setToast(Toast.makeText(context, text, Toast.LENGTH_LONG));
        activity.getToast().show();
    }

    public static void toastError(Context context, Throwable throwable) {
        EventBus.getDefault().post(new DialogDismissMessage(Constants.EVENT_BUS_TIME_OUT_MESSAGE));
        if (throwable.getCause() instanceof SocketTimeoutException) {
            showToast(
                    context,
                    SystemFramework.getInstance().getGlobalContext()
                            .getString(R.string.network_timeout), false);
            return;
        }
        if (throwable instanceof RuntimeException) {
            if (throwable.getMessage().contains("Unable to resolve host")) {
                showToast(
                    context,
                    SystemFramework.getInstance().getGlobalContext()
                        .getString(R.string.network_error), false);
            } else {
                showToast(context, throwable.getMessage(), false);
            }
            return;
        }

        toastError(context, throwable,
                SystemFramework.getInstance().getGlobalContext().getString(R.string.network_error));
    }

    public static void toastError(Context context, Throwable throwable, String errorType) {
        showToast(context, errorType + ": " + throwable.getMessage(), false);
    }

    public static void checkForError(BaseResponse response) {
        if (!response.hasError()) {
            return;
        }

        String message = Strings.isNullOrEmpty(response.error.message) ?
            String.valueOf(response.error.code) :
            response.error.message;
        throw new RuntimeException(message);
    }

    public static boolean isFastDoubleClick() {
        return isFastDoubleClick(300);
    }

    public static boolean isFastDoubleClick(long timeSpace) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        lastClickTime=time;
        if (0 < timeD && timeD < timeSpace) {
            return true;
        }
        return false;
    }

    /**
     * 更新购物车上的文字显示
     */
    public static void updateCartDescription(Activity mActivity, Enum type) {
        if(mActivity != null && mActivity instanceof YMXMainActivity&&CartManager.getInstance().isUserLogin()) {
            YMXMainActivity activity = (YMXMainActivity)mActivity;
            if(activity == null || activity.mCartContent == null || activity.mCartDetailContent == null) {
                return ;
            }
            if (DataManager.getInstance().get(CacheKeys.TOKEN) == null){
                activity.mCartContent.setVisibility(View.GONE);
                activity.mCartDetailContent.setVisibility(View.GONE);
                return;
            }
            CartUpdate cartUpdate = CartManager.getInstance().mCartUpdate;
            if(cartUpdate != null && cartUpdate.total != null) {
                activity.mCartContent.setVisibility(View.GONE);
                activity.mCartDetailContent.setVisibility(View.GONE);
                //首页
                if (Constants.PageType.HOME == type){
                    if(cartUpdate.total.count > 0) {
                        activity.mCartContent.setVisibility(View.VISIBLE);
                        activity.mCartContent.setText(StringUtils.isEmpty(cartUpdate.total.totalPrice) ?
                            "" : cartUpdate.total.totalPrice);
                    }
                }
                //活动专场
                if (Constants.PageType.SESSION == type){
                    if(cartUpdate.total.count > 0) {
                        activity.mCartDetailContent.setVisibility(View.VISIBLE);
                        activity.mCartDetailContent.setText(StringUtils.isEmpty(cartUpdate.total.totalPrice) ?
                                "" : cartUpdate.total.totalPrice);
                    }
                }
                //分类页面
                if (Constants.PageType.CATEGORY == type) {
                    if(cartUpdate.total.count > 0) {
                        activity.mCartContent.setVisibility(View.VISIBLE);
                        activity.mCartContent.setText(StringUtils.isEmpty(cartUpdate.total.totalPrice) ?
                                "" : cartUpdate.total.totalPrice);
                    }
                }
            }
        }
        if(mActivity != null && mActivity instanceof SearchActivity&&CartManager.getInstance().isUserLogin()) {
            SearchActivity searchActivity = (SearchActivity) mActivity;
            if(searchActivity != null) {
                Fragment fragment = searchActivity.getSearchFragment();
                if(fragment != null && fragment instanceof SearchFragment) {
                    SearchFragment searchFragment = (SearchFragment)fragment;
                    if(searchFragment == null || searchFragment.mCartDetailContent == null) {
                        return ;
                    }
                    if (DataManager.getInstance().get(CacheKeys.TOKEN) == null){
                        searchFragment.mCartDetailContent.setVisibility(View.GONE);
                        return;
                    }
                    CartUpdate cartUpdate = CartManager.getInstance().mCartUpdate;
                    if(cartUpdate != null && cartUpdate.total != null) {
                        if (Constants.PageType.SEARCH == type) {
                            if (cartUpdate.total.count > 0) {
                                searchFragment.mCartDetailContent.setVisibility(View.VISIBLE);
                                searchFragment.mCartDetailContent.setText(StringUtils.isEmpty(cartUpdate.total.totalPrice) ?
                                        "" : cartUpdate.total.totalPrice);
                            } else {
                                searchFragment.mCartDetailContent.setVisibility(View.GONE);
                            }
                        }
                    }
                }
            }
        }

        if(mActivity != null && mActivity instanceof CouDanActivity && CartManager.getInstance().isUserLogin()) {
            CouDanActivity couDanActivity = (CouDanActivity) mActivity;
            if(couDanActivity != null) {
                Fragment fragment = couDanActivity.getHuanGouFragment();
                if(fragment != null && fragment instanceof CouDanFragment) {
                    CouDanFragment couDanFragment = (CouDanFragment)fragment;
                    if(couDanFragment == null || couDanFragment.mCartDetailContent == null) {
                        return ;
                    }
                    if (DataManager.getInstance().get(CacheKeys.TOKEN) == null){
                        couDanFragment.mCartDetailContent.setVisibility(View.GONE);
                        return;
                    }
                    CartUpdate cartUpdate = CartManager.getInstance().mCartUpdate;
                    if(cartUpdate != null && cartUpdate.total != null) {
                        if (Constants.PageType.SEARCH == type) {
                            if (cartUpdate.total.count > 0) {
                                couDanFragment.mCartDetailContent.setVisibility(View.VISIBLE);
                                couDanFragment.mCartDetailContent.setText(StringUtils.isEmpty(cartUpdate.total.totalPrice) ?
                                        "" : cartUpdate.total.totalPrice);
                            } else {
                                couDanFragment.mCartDetailContent.setVisibility(View.GONE);
                            }
                        }
                    }
                }
            }
        }

        if(mActivity != null && mActivity instanceof HuanGouActivity && CartManager.getInstance().isUserLogin()) {
            HuanGouActivity huanDanActivity = (HuanGouActivity) mActivity;
            if(huanDanActivity != null) {
                Fragment fragment = huanDanActivity.getHuanGouFragment();
                if(fragment != null && fragment instanceof HuanGouFragment) {
                    HuanGouFragment huanGouFragment = (HuanGouFragment)fragment;
                    if(huanGouFragment == null || huanGouFragment.mCartDetailContent == null) {
                        return ;
                    }
                    if (DataManager.getInstance().get(CacheKeys.TOKEN) == null){
                        huanGouFragment.mCartDetailContent.setVisibility(View.GONE);
                        return;
                    }
                    CartUpdate cartUpdate = CartManager.getInstance().mCartUpdate;
                    if(cartUpdate != null && cartUpdate.total != null) {
                        if (Constants.PageType.SEARCH == type) {
                            if (cartUpdate.total.count > 0) {
                                huanGouFragment.mCartDetailContent.setVisibility(View.VISIBLE);
                                huanGouFragment.mCartDetailContent.setText(StringUtils.isEmpty(cartUpdate.total.totalPrice) ?
                                        "" : cartUpdate.total.totalPrice);
                            } else {
                                huanGouFragment.mCartDetailContent.setVisibility(View.GONE);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 最近刷新的时间
     * @param object
     */
    public static void setLastFlushTime(Object object){
        if (timeMap == null)  timeMap = new HashMap<>();
        if (object == null ||
                StringUtils.isEmpty(object.getClass().getName())) return;
        timeMap.put(object.getClass().getName(), System.currentTimeMillis());
    }

    /**
     * 一段间隔后是否需要刷新
     * @param object
     * @return
     */
    public static boolean isNeedFlush(Object object){
        if (timeMap == null)  timeMap = new HashMap<>();
        if (object == null ||
                StringUtils.isEmpty(object.getClass().getName()) ||
                !timeMap.containsKey(object.getClass().getName())) return false;

        long time = System.currentTimeMillis() - timeMap.get(object.getClass().getName());
        if (time > intevalTime){
            timeMap.put(object.getClass().getName(), System.currentTimeMillis());
            return true;
        }else{
            return false;
        }
    }

    /**
     * 一段间隔后首页是否显示通知notice
     * @param storeId
     * @return
     */
    public static boolean isNeedNotice(String storeId){
        if (storeId == null)  return true;
        long last = SharedPreferencesHelper.getLong(storeId, 0);
        if (last == 0){
            return true;
        }
        long time = System.currentTimeMillis() - last;
        if (time > noticeTime) {
            return true;
        }
        else return false;
    }

    /**
     * 匹配市（该方法旨在服务器传递城市不带 市  字符）
     * @param transfer 传递过来的城市名称
     * @param source 数据源
     * @return
     */
    public static boolean isCompareCity(String transfer, String source){
        if (!StringUtils.isEmpty(transfer) && !StringUtils.isEmpty(source)){
            if (!transfer.endsWith("市")) transfer = transfer + "市";
            if (!source.endsWith("市")) source = source + "市";
            if (transfer.equals(source)) return true;
            else return false;
        }else {
            return false;
        }
    }
    /**
     * 匹配省（该方法旨在服务器传递省不带 市或者省  字符）
     * @param transfer 传递过来的城市名称
     * @param source 数据源
     * @return
     */
    public static boolean isCompareProvince(String transfer, String source){
        if (!StringUtils.isEmpty(transfer) && !StringUtils.isEmpty(source)){
            if (transfer.endsWith("省") || !transfer.endsWith("市"))
                transfer = transfer.substring(0, transfer.length() - 1);
            if (source.endsWith("省") && transfer.endsWith("市"))
                source = source.substring(0, source.length() - 1);
            if (transfer.equals(source)) return true;
            else return false;
        }else {
            return false;
        }
    }

    /**
     * 关闭软键盘
     * @param activity
     */
    public static void closeSoftKeyBoard(Activity activity) {
        if(activity == null) {
            return ;
        }
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 开启软键盘
     * @param activity
     */
    public static void openSoftKeyBoard(Activity activity,View view) {
        if(activity == null) {
            return ;
        }
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        }
    }

    public static boolean isShowHomeAd(Context context, String url){
        if (context == null) return false;
        if (StringUtils.isEmpty(url)) {
            return false;
        }
        long last = SharedPreferencesHelper.getLong("ad_home_time", 0);
        long now = System.currentTimeMillis();
        if (last <= 0 || now - last >= AdShowTime){
            return true;
        }else{
            return false;
        }
    }

    /**显示缩放动画*/
    public static void showScaleAnimation(final View view){
        final AnimationSet set = new AnimationSet(true);
        final ScaleAnimation anim = new ScaleAnimation(1f,1.2f,1f,1.2f ,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        final ScaleAnimation anim2 = new ScaleAnimation(1.2f,1f,1.2f,1f ,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }
            @Override
            public void onAnimationEnd(Animation animation) {
                anim2.setFillAfter(false);
                anim2.setDuration(100);
                anim2.setInterpolator(new LinearInterpolator());
                view.startAnimation(anim2);
            }
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        anim.setFillAfter(true);
        anim.setDuration(100);
        anim.setInterpolator(new LinearInterpolator());
        view.startAnimation(anim);
    }

    /**显示缩放动画*/
    public static void showScaleAnimation(View view,float fromX,float toX,float fromY,float toY,int duration,boolean fillAfter,Animation.AnimationListener listener){
        ScaleAnimation anim = new ScaleAnimation(fromX,toX,fromY,toY ,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        anim.setFillAfter(fillAfter);
        anim.setDuration(duration);
//        anim.setRepeatCount(1);
//        anim.setRepeatMode(Animation.REVERSE);
        if(null!=listener)anim.setAnimationListener(listener);
        view.startAnimation(anim);
    }

    /**设置删除时显示dialog的动画*/
    public static void setHierarchyChangeListener(ViewGroup view,final Context context){
        view.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
            MessageDialogView mdv;

            @Override
            public void onChildViewAdded(final View parent, final View child) {
                if (child instanceof MessageDialogView) {
                    mdv = (MessageDialogView) child;
                    mdv.mFlDialogContainer.setBackgroundColor(context.getResources().getColor(R.color.dialog_transparent_color));
                    AlphaAnimation aa = new AlphaAnimation(0f, 1f);
                    aa.setFillAfter(true);
                    aa.setDuration(400);
                    mdv.mFlDialogContainer.startAnimation(aa);
                    showScaleAnimation(mdv.mLlDialogContainer, 0f, 1f, 0f, 1f, 400, false, null);
                }
            }

            @Override
            public void onChildViewRemoved(View parent, View child) {
                AlphaAnimation aa = new AlphaAnimation(1f, 0f);
                aa.setFillAfter(true);
                aa.setDuration(100);
                mdv.mFlDialogContainer.startAnimation(aa);
            }
        });
    }
    /**给所有dialog加动画*/
    public static void showAlertDialog(AlertDialog.Builder builder){
        AlertDialog dialog = builder.create();
        dialog.getWindow().setWindowAnimations(R.style.popup_in_center);
        dialog.show();
    }
    /**dialog加动画*/
    public static void showAlertDialog(Dialog dialog){
        dialog.getWindow().setWindowAnimations(R.style.popup_in_center);
        dialog.show();
    }

    public static Bitmap drawable2Bitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof NinePatchDrawable) {
            Bitmap bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        } else {
            return null;
        }
    }

    /**
     * 毛玻璃模糊化效果
     * @param sentBitmap 原始图片
     * @param radius 模糊半径
     * @param canReuseInBitmap 是否使用当前图片做修改(true再当前图片上模糊化， false返回新的模糊图片原始图片芿保留)
     * @return
     */
    public static Bitmap doBlur(Bitmap sentBitmap, int radius,
                                boolean canReuseInBitmap) {

        Bitmap bitmap;
        if (canReuseInBitmap) {
            bitmap = sentBitmap;
        } else {
            bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
        }

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16)
                        | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

        return (bitmap);
    }

    public static Bitmap getIconCircleBitmap(Context context, Bitmap sourceBm, float ringWidthInPix){
        int width = sourceBm.getWidth();
        int height = sourceBm.getHeight();
        float radius = width > height ? height / 2 : width / 2;
        float centerX = width / 2;
        float centerY = height / 2;
        Bitmap bm_circle = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas_circle = new Canvas(bm_circle);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        canvas_circle.drawCircle(centerX, centerY, radius, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas_circle.drawBitmap(sourceBm, 0, 0, paint);
        if(ringWidthInPix > 0){
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(ringWidthInPix / 2);
            paint.setColor(context.getResources().getColor(R.color.ymx_orange));
            canvas_circle.drawCircle(centerX, centerY, radius, paint);
        }
        Matrix matrix = new Matrix();
        float temp = context.getResources().getDisplayMetrics().density * 40;
        matrix.setScale(temp / width, temp / height);
        return Bitmap.createBitmap(bm_circle, 0, 0, width, height, matrix, true);
    }

    public static Bitmap effectBitmap;

    public static void showEffectDialog(Context context, int requestCode, ArrayList<PromotionInfo> proList){
        FrameLayout frame = (FrameLayout) ((Activity) context).getWindow().findViewById(Window.ID_ANDROID_CONTENT);
        Bitmap bm = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bm);
        frame.draw(canvas);
        if(effectBitmap != null)
            effectBitmap.recycle();
        effectBitmap = bm;
        Intent intent = new Intent(context, DialogEffectActivity.class);
        intent.putExtra("data", proList);
        ((Activity) context).startActivityForResult(intent, requestCode);
        ((Activity) context).overridePendingTransition(0, 0);
    }


}
